package cn.charlotte.pit.listener;

import cn.charlotte.pit.commands.admin.TrashBin;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;

public class TrashBinListener implements Listener {

    @EventHandler
    public void onInventoryClick(InventoryClickEvent event) {
        if (event.getView().getTitle().equals(TrashBin.INVENTORY_TITLE)) {
            event.setCancelled(true);
            Optional.ofNullable(event.getCurrentItem())
                    .filter(l -> event.isLeftClick())
                    .filter(l -> !l.isEmpty())
                    .filter(l -> !l.hasItemMeta() || !l.getItemMeta().hasDisplayName())
                    .ifPresent(l -> moveItem(event.getView(), event.getRawSlot(), l));
        }
    }

    private void moveItem(@NotNull InventoryView view, int rawSlot, ItemStack l) {
        Inventory container = view.getTopInventory();
        if (rawSlot < container.getSize()) {
            container = view.getBottomInventory();
        }
        container.addItem(l.clone());
        l.setAmount(0);
        l.setType(Material.AIR);
    }
}